<template>
  <div>
    <!--面包屑导航区-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!--卡片视图区域-->
    <el-card>
      <!--提示区域-->
      <el-alert title="添加商品信息"
                type="info" center :closable="false" show-icon>
      </el-alert>
      <!--步骤条区域-->
      <el-steps :space="200" :active="activeIndex - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!--tab栏区域-->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef"
               label-width="100px" label-position="top">
        <el-tabs v-model="activeIndex" :tab-position="'left'" :before-leave="beforeTabLeave" @tab-click="tabClicked">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="addForm.name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="price">
              <el-input v-model="addForm.price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="weight">
              <el-input v-model="addForm.weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="count">
              <el-input v-model="addForm.count" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="cate_id">
              <el-cascader v-model="addForm.cate_id"
                           :options="catelist"
                           :props="cascaderProps"
                           @change="CateChanged" clearable>
              </el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!--渲染表单的Item项-->
            <el-form-item :label="item.name" v-for="item in manyTableData" :key="item.id">
              <!--复选框组-->
              <el-checkbox-group v-model="selectmanyTableData">
                <el-checkbox border :label="cb" v-for="(cb, i) in item.val" :key="i" checked @change="manyValData" :dataid="item.id"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.name" v-for="item in onlyTableData" :key="item.id">
              <el-input v-model="item.val"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!--action 表示图片要上传到后台的API地址-->
            <el-upload :action="uploadURL" :on-preview="handlePreview"
                       :on-remove="handleRemove"
                       list-type="picture" :headers="headerObj" :on-success="handleSuccess">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!--富文本编辑器组件-->
            <quill-editor v-model="addForm.intriduce"></quill-editor>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <div class="BtnZu">
        <el-button type="primary" :class="activeIndex - 0 === 0 ? 'HideStyle' : ''" @click="prev">上一步</el-button>
        <el-button type="primary" :class="activeIndex - 0 === 4 ? 'HideStyle' : ''" @click="next" :disabled="isBtnDisabled" >下一步</el-button>
        <el-button type="primary" :class="['btnAdd', activeIndex - 0 === 4 ? '' : 'HideStyle']" @click="add">编辑完成</el-button>
      </div>
    </el-card>
    <!--图片预览-->
    <el-dialog title="图片预览"
               :visible.sync="previewVisible"
               width="50%">
      <img :src="previewPath" alt="" class="previewImg" />
    </el-dialog>
  </div>
</template>

<script>
  import _ from 'lodash'
  export default {
    data() {
      return {
        activeIndex: '0',
        // 添加商品的表单数据对象
        addForm: {
          name: '',
          price: 0,
          weight: 0,
          count: 0,
          // 级联选择框双向绑定到的数组
          cate_id: [],
          // 图片的数组
          pics: [],
          // 商品的详情描述
          intriduce: '',
          attrs: []
        },
        addFormRules: {
          name: [
            { required: true, message: '请输入商品名称', trigger: 'blur' }
          ],
          price: [
            { required: true, message: '请输入商品价格', trigger: 'blur' }
          ],
          weight: [
            { required: true, message: '请输入商品重量', trigger: 'blur' }
          ],
          count: [
            { required: true, message: '请输入商品数量', trigger: 'blur' }
          ],
          cate_id: [
            { required: true, message: '请选择商品分类', trigger: 'blur' }
          ]
        },
        // 商品分类数据
        catelist: [],
        // 指定级联选择器的配置对象
        cascaderProps: {
          expandTrigger: 'hover',
          value: 'id',
          label: 'name',
          children: 'children',
          checkStrictly: true
        },
        // 动态参数列表
        manyTableData: [],
        // 选中的动态参数列表
        selectmanyTableData: [],
        // 静态属性列表
        onlyTableData: [],
        // 上传图片的URL地址
        uploadURL: 'https://localhost:44301/Main/UpLoadGoodsPhotos',
        // 图片上传组件的headers请求头对象
        headerObj: {
          Authorization: window.sessionStorage.getItem('token')
        },
        // 图片预览路径
        previewPath: '',
        // 预览图片模态框显示与隐藏
        previewVisible: false,
        // 将要提交的动态商品参数数据
        copyManyData: [],
        // 未选择三级分类禁用下一步按钮
        isBtnDisabled: true
      }
    },
    created() {
      this.getCateList()
    },
    methods: {
      // 获取所有商品分类列表
      async getCateList() {
        const { data: res } = await this.$http.get('GetCateParentList')
        if (!res.state) {
          return this.$message.error(res.text)
        }
        for (var i = 0; i < res.data.length; i++) {
          if (res.data[i].children.length !== 0) {
            for (var j = 0; j < res.data[i].children.length; j++) {
              if (res.data[i].children[j].children.length === 0) {
                delete res.data[i].children[j].children
              }
            }
          } else {
            delete res.data[i].children
          }
        }
        this.catelist = res.data
      },
      // 级联选择器选中项变化，触发事件
      CateChanged() {
        if (this.addForm.cate_id.length !== 3) {
          this.addForm.cate_id = []
          this.isBtnDisabled = true
        } else {
          this.isBtnDisabled = false
        }
      },
      // 判断未选择商品分类不能进行下一步
      beforeTabLeave(activeName, oldActiveName) {
        if (oldActiveName === '0' && this.addForm.cate_id.length !== 3) {
          this.$message.error('请选择商品分类')
          return false
        }
      },
      // 点击左侧tab栏
      async tabClicked() {
        // 访问动态参数面板
        if (this.activeIndex === '1') {
          const { data: res } = await this.$http.post('GetCateParms', { cateId: this.cateId, type: 'many' })
          if (!res.state) {
            return this.$message.error(res.text)
          }
          res.data.forEach(item => {
            if (item.val.length !== 0) {
              const newVal = []
              item.val.forEach(items => {
                newVal.push(items.name)
              })
              item.val = newVal
            }
          })
          this.manyTableData = res.data
        } else if (this.activeIndex === '2') {
          // 访问静态属性面板
          const { data: res } = await this.$http.post('GetCateParms', { cateId: this.cateId, type: 'only' })
          if (!res.state) {
            return this.$message.error(res.text)
          }
          res.data.forEach(item => {
            if (item.val.length !== 0) {
              let newVal = ''
              item.val.forEach(items => {
                newVal += items.name + '  '
              })
              item.val = newVal.trim()
            }
          })
          this.onlyTableData = res.data
        }
      },
      // 处理图片预览效果
      handlePreview(file) {
        this.previewPath = file.response.data.url
        this.previewVisible = true
      },
      // 处理移除图片的操作
      async handleRemove(file) {
        const filePath = file.response.data.tmp_path
        const { data: res } = await this.$http.post('RemoveServerPhotos', { path: filePath })
        if (!res.state) {
          this.$message.error(res.text)
          return false
        }
        const i = this.addForm.pics.findIndex(x => x.pic === filePath)
        this.addForm.pics.splice(i, 1)
      },
      // 监听图片上传成功的事件
      handleSuccess(response) {
        const picInfo = { pic: response.data.tmp_path }
        this.addForm.pics.push(picInfo)
      },
      // 添加商品
      add() {
        this.$refs.addFormRef.validate(async valid => {
          if (!valid) {
            return this.$message.error('请填写必要的表单项！')
          }
          this.copyManyData.forEach(item => {
            const newInfo = { id: item.id, val: item.val.join('  '), type: 'many' }
            this.addForm.attrs.push(newInfo)
          })
          this.onlyTableData.forEach(item => {
            const newInfo = { id: item.id, val: item.val, type: 'only' }
            this.addForm.attrs.push(newInfo)
          })
          // lodash cloneDeep(obj)
          const form = _.cloneDeep(this.addForm)
          form.cate_id = form.cate_id.join(',')
          form.attrs = JSON.stringify(form.attrs)
          form.pics = JSON.stringify(form.pics)

          const { data: res } = await this.$http.post('AddGoods', form)
          if (!res.state) {
            return this.$message.error(res.text)
          }
          this.$message.success(res.text)
          this.$router.push('/goods')
        })
      },
      manyValData(select, val) {
        // 商品动态参数id
        const paramsid = val.path[0].parentNode.parentNode.getAttribute('dataid')
        // 商品动态参数项值
        const paramsVal = val.path[0].value
        if (this.copyManyData.length === 0) {
          this.copyManyData.push({ id: paramsid, val: [paramsVal] })
        } else {
          const same = this.copyManyData.findIndex(i => i.id === paramsid)
          if (same < 0) {
            this.copyManyData.push({ id: paramsid, val: [paramsVal] })
          } else {
            this.copyManyData.forEach(item => {
              if (parseInt(item.id) === parseInt(paramsid)) {
                if (select) {
                  const i = item.val.findIndex(x => x === paramsVal)
                  if (i < 0) {
                    item.val.push(paramsVal)
                  }
                } else {
                  const i = item.val.findIndex(x => x === paramsVal)
                  item.val.splice(i, 1)
                }
              }
            })
          }
          console.log(this.copyManyData)
        }
      },
      // 点击按钮返回上一步
      prev() {
        let index = parseInt(this.activeIndex)
        if (index > 0 && index <= 4) {
          index -= 1
          this.activeIndex = index + ''
          if (index === 1 || index === 2) {
            this.tabClicked()
          }
        }
      },
      // 点击按钮进行下一步
      next() {
        let index = parseInt(this.activeIndex)
        if (index >= 0 && index < 4) {
          index += 1
          this.activeIndex = index + ''
          if (index === 1 || index === 2) {
            this.tabClicked()
          }
        }
      }
    },
    computed: {
      cateId() {
        if (this.addForm.cate_id.length === 3) {
          return this.addForm.cate_id[2]
        }
        return null
      }
    }
  }
</script>

<style lang="less" scoped>
  .el-checkbox{
    margin: 5px 10px 0 0 !important;
  }
  .previewImg{
    width: 100%
  }
  .btnAdd {
    margin-top: 15px;
  }

  .BtnZu {
    margin-top: 10px;
    text-align: center;
  }

  .HideStyle {
    display: none;
  }
</style>
